package com.zkkz.boot.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @Auth:Chan
 * 配置跨域的文件，该部分主要解决客户端请求进入到服务端时的跨域处理
 */
@Configuration
@Slf4j
public class GlobalCorsConfig {
    /**
     * 为了安全，建议只放行需要的地址(可以再yaml中定义进行映射方便扩展)
     */
    private List<String> sourceCors =Arrays.asList();// Arrays.asList("http://localhost:8081", "http://localhost:8082", "http://localhost:8083", "http://localhost:8084");
    private List<String> methods = Arrays.asList();// Arrays.asList("HEAD","GET", "POST", "PUT", "DELETE", "OPTIONS","PATCH");

    @Bean
    public CorsWebFilter corsWebFilter() {

        log.info("CorsWebFilter===============");
        CorsConfiguration config = new CorsConfiguration();

        // 放行原始域
        if (CollectionUtils.isEmpty(sourceCors)) {
            // 放行所有
            //config.addAllowedOrigin("*");      //允许跨域访问的域名，可填写具体域名，*代表允许所有访问
            config.addAllowedOriginPattern("*"); //spring boot 2.4.0版本之前方法名为allowedOrigins()
        } else {
            for (String sourceCor : sourceCors) {
                config.addAllowedOrigin(sourceCor);
            }
        }
        // 放行请求头
        if (CollectionUtils.isEmpty(methods)) {
            // 放行所有
            config.addAllowedHeader("*");
        } else {
            //放行指定请求头
            for (String method : methods) {
                config.addAllowedHeader(method);
            }
        }
        // 是否发送cookie
        config.setAllowCredentials(true);
        // 放行请求方式
        config.addAllowedMethod("*");
        // 暴露头部信息
        config.addExposedHeader("*");
        config.setMaxAge(36000L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

    @Bean
    public CorsResponseHeaderFilter corsResponseHeaderFilter() {
        return new CorsResponseHeaderFilter();
    }
}